<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <!-- 账号输入框 -->
                <el-form-item label="账号" prop="account">
                    <el-input
                        v-model="formData.account"
                        :disabled="formData.root == 1"
                        placeholder="请输入账号"
                        clearable
                    />
                </el-form-item>
                <!-- 管理员头像 -->
                <el-form-item label="头像">
                    <div>
                        <div>
                            <material-picker v-model="formData.avatar" :limit="1" />
                        </div>
                        <div class="form-tips">建议尺寸：100*100px，支持jpg，jpeg，png格式</div>
                    </div>
                </el-form-item>

                <!-- 密码输入框 -->
                <el-form-item label="密码" prop="password">
                    <el-input
                        v-model="formData.password"
                        show-password
                        clearable
                        placeholder="请输入密码"
                    />
                </el-form-item>

                <!-- 确认密码输入框 -->
                <el-form-item label="确认密码" prop="password_confirm">
                    <el-input
                        v-model="formData.password_confirm"
                        show-password
                        clearable
                        placeholder="请输入确认密码"
                    />
                </el-form-item>
                <!-- 名称输入框 -->
                <el-form-item label="代理商名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入代理商名称" clearable />
                </el-form-item>
                <!-- 手机号输入框 -->
                <el-form-item label="手机号" prop="mobile">
                    <el-input
                        v-model="formData.mobile"
                        placeholder="请输入手机号"
                        clearable
                        @input="handleMobileInput"
                    />
                </el-form-item>
                <el-form-item label="联系地址" prop="contact">
                    <el-input
                        class="flex-1"
                        v-model="formData.contact"
                        type="textarea"
                        rows="4"
                        clearable
                        placeholder="请输入联系地址"
                    />
                </el-form-item>
                <el-form-item label="邮箱地址" prop="email">
                    <el-input v-model="formData.email" clearable placeholder="请输入邮箱地址" />
                </el-form-item>
                <!-- 状态 -->
                <el-form-item label="状态" v-if="formData.root != 1">
                    <el-switch v-model="formData.disable" :active-value="0" :inactive-value="1" />
                </el-form-item>
                <el-form-item label="返点" prop="rebate">
                    <el-input v-model="formData.rebate" clearable placeholder="请输入返点" />
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="agentsEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiAgentsAdd, apiAgentsEdit, apiAgentsDetail } from '@/api/agents'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑代理商表' : '新增代理商表'
})

// 表单数据
const formData = reactive({
    agent_id: '',
    uid: '',
    account: '',
    avatar: '',
    password: '',
    password_confirm: '',
    name: '',
    contact: '',
    email: '',
    disable: 0,
    rebate: '',
    mobile: ''
})

// 手机号输入过滤
const handleMobileInput = (value: string) => {
    formData.mobile = value.replace(/\D/g, '') // 过滤非数字字符
}

const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}

// 表单验证
const formRules = reactive<any>({
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入代理商名称',
            trigger: ['blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ] as any[],
    password_confirm: [
        {
            required: true,
            message: '请输入确认密码',
            trigger: ['blur']
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[],
    contact: [
        {
            required: true,
            message: '请输入联系地址',
            trigger: ['blur']
        }
    ],
    email: [
        {
            required: true,
            message: '请输入邮箱地址',
            trigger: ['blur']
        }
    ],
    rebate: [
        {
            required: true,
            message: '请输入返点',
            trigger: ['blur']
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入手机号',
            trigger: ['blur']
        }
    ]
})

// 获取详情
const setFormData = async (row: any) => {
    formRules.password = []
    formRules.password_confirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    const data = await apiAgentsDetail({
        agent_id: row.agent_id
    })
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiAgentsDetail({
        agent_id: row.agent_id
    })
    setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    const data = { ...formData }
    mode.value == 'edit' ? await apiAgentsEdit(data) : await apiAgentsAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
